package com.bowlong.io;

import java.io.DataOutput;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class ByteBufferOutputStream extends OutputStream implements DataOutput {
	ByteBuffer out;

	final byte TRUE = 1;
	final byte FALSE = 0;

	public ByteBufferOutputStream(ByteBuffer buff) {
		this.out = buff;
	}

	@Override
	public void writeBoolean(boolean v) throws IOException {
		out.put(v ? TRUE : FALSE);
	}

	@Override
	public void writeByte(int v) throws IOException {
		byte val = (byte) v;
		out.put(val);
	}

	@Override
	public void writeShort(int v) throws IOException {
		short val = (short) v;
		out.putShort(val);
	}

	@Override
	public void writeChar(int v) throws IOException {
		char val = (char) v;
		out.putChar(val);
	}

	@Override
	public void writeInt(int v) throws IOException {
		out.putInt(v);
	}

	@Override
	public void writeLong(long v) throws IOException {
		out.putLong(v);
	}

	@Override
	public void writeFloat(float v) throws IOException {
		out.putFloat(v);
	}

	@Override
	public void writeDouble(double v) throws IOException {
		out.putDouble(v);
	}

	@Override
	public void writeBytes(String s) throws IOException {
		byte[] bs = s.getBytes();
		out.putInt(bs.length);
		out.put(bs);
	}

	@Override
	public void writeChars(String s) throws IOException {
		byte[] bs = s.getBytes();
		out.putInt(bs.length);
		out.put(bs);
	}

	@Override
	public void writeUTF(String s) throws IOException {
		byte[] bs = s.getBytes("UTF-8");
		out.putInt(bs.length);
		out.put(bs);
	}

	@Override
	public void write(int b) throws IOException {
		byte val = (byte) b;
		out.put(val);
	}

	public int postion() {
		return out.position();
	}

	public void postion(int pos) {
		out.position(pos);
	}

	@Override
	public void close() throws IOException {
		out.clear();
	}

}
